package com.amphiprion.prototype.component;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;

import com.amphiprion.prototype.ScreenProperty;
import com.amphiprion.prototype.control.ControlerState;
import com.amphiprion.prototype.control.ControlerState.ClickMode;

public class ButtonComponent extends ImageComponent {
	private String text;
	private int color;
	private float textSize;
	private Paint paintText;
	private IActionListener listener;

	public ButtonComponent(String imageUri, float x, float y, int alpha) {
		this(null, 20.0f, Color.BLACK, imageUri, x, y, alpha);
	}

	public ButtonComponent(String text, float textSize, int color, String imageUri, float x, float y, int alpha) {
		super(imageUri, x, y, alpha);
		this.text = text;
		this.color = color;
		this.textSize = textSize;
		paintText = new Paint();
		paintText.setColor(color);
		paintText.setTextSize(textSize);
		paintText.setFakeBoldText(true);
		paintText.setAntiAlias(true);
	}

	@Override
	public void onInput(ControlerState state, long elapsed) {
		super.onInput(state, elapsed);
		if (listener != null) {
			if (state.click == ClickMode.DOWN && alpha != 0 && !state.consumed) {
				if (isInside(state.position.x, state.position.y)) {
					state.consumed = true;
					listener.actionPerformed(this);
				}
			}
		}
	}

	@Override
	public void onDraw(Canvas canvas, ScreenProperty screenProperty) {
		if (alpha == 0) {
			return;
		}
		super.onDraw(canvas, screenProperty);
		if (text != null) {
			drawText(canvas, text, x, y, scale, screenProperty);
		}
	}

	private void drawText(Canvas canvas, String str, float centerX, float centerY, float scale, ScreenProperty screenProperty) {

		paintText.setAlpha(alpha);
		float pSize = paintText.getTextSize();
		// if ("center".equals(alignment)) {
		centerX -= scale * paintText.measureText(str) / 2;
		// }
		paintText.setTextSize(pSize * screenProperty.screenScale * scale);
		Matrix m = new Matrix();
		// m.postTranslate(-canvas.getWidth() / 2, -canvas.getHeight() / 2);
		m.postRotate(screenProperty.screenRotation);
		if (screenProperty.screenRotation == 0) {
			// m.postTranslate(canvas.getWidth() / 2, canvas.getHeight() / 2);
		} else {
			m.postTranslate(canvas.getWidth(), 0);
		}
		float txtX;
		float txtY;
		txtX = centerX * screenProperty.screenScale;
		txtY = centerY * screenProperty.screenScale;
		txtY += pSize * 0.3 * screenProperty.screenScale * scale;

		canvas.save();
		canvas.setMatrix(m);
		canvas.drawText(str, txtX - screenProperty.screenOffsetX, txtY - screenProperty.screenOffsetY, paintText);
		// canvas.drawRect(0, 0, 400, 240, paint);
		canvas.restore();
		paintText.setTextSize(pSize);

	}

	public void setActionListener(IActionListener listener) {
		this.listener = listener;
	}
}
